package org.smarthings.impl;

import java.util.Dictionary;

import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Service;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventConstants;
import org.osgi.service.event.EventHandler;
import org.smarthings.Utils;
import org.smarthings.things.management.event.ThingEventConstants;

@Component
@Service(EventHandler.class)
@SuppressWarnings("unchecked")
@Property(name = EventConstants.EVENT_TOPIC, value = { ThingEventConstants.TOPIC_THING_STATE_CHANGED,
		ThingEventConstants.TOPIC_THING_PROPERTY_CHNAGED, ThingEventConstants.TOPIC_THING_ACTION_EXECUTED })
public class EventHandlerImpl implements EventHandler {
	public void handleEvent(Event event) {
		// TODO handle registrations and rules, too, so that the duplicates map should be cleaned up
		String uri = null;
		Dictionary<String, Object> thing = ((Dictionary<String, Object>) event
				.getProperty(ThingEventConstants.PROPERTY_THING));
		switch (event.getTopic()) {
		case ThingEventConstants.TOPIC_THING_STATE_CHANGED:
			uri = "services/things/" + thing.get(ThingEventConstants.PROPERTY_THING_UUID) + "/state";
			break;
		case ThingEventConstants.TOPIC_THING_PROPERTY_CHNAGED:
			Dictionary<String, Object> property = (Dictionary<String, Object>) event
					.getProperty(ThingEventConstants.PROPERTY_THING_CHANGED_PROPERTY);
			uri = "services/things/" + thing.get(ThingEventConstants.PROPERTY_THING_UUID) + "/properties/"
					+ property.get(ThingEventConstants.PROPERTY_THING_CHANGED_PROPERTY_UUID) + "/value";
			break;
		case ThingEventConstants.TOPIC_THING_ACTION_EXECUTED:
			Dictionary<String, Object> action = (Dictionary<String, Object>) event
					.getProperty(ThingEventConstants.PROPERTY_THING_EXECUTED_ACTION);
			uri = "services/things/" + thing.get(ThingEventConstants.PROPERTY_THING_UUID) + "/actions/executions/"
					+ action.get(ThingEventConstants.PROPERTY_THING_EXECUTED_ACTION_UUID) + "/arguments";
			break;
		}

		if (uri != null) {
			uri = Utils.normalizeUri(uri);
			MessageBrokerImpl.getInstance().update(uri);
		}
	}
}